package com.gome.ocean.controller.gddl.app.group;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.gddl.GroupBO;
import com.gome.ocean.dao.model.gddl.GroupRuleBO;
import com.gome.ocean.service.base.BaseController;
import com.gome.ocean.service.gddl.GroupRuleService;
import com.gome.ocean.service.gddl.GroupService;


/**
 * Created by liuqingxia on 2016/3/24.
 */
@Controller
@RequestMapping("/tddl/groupRule")
public class GroupRuleController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(GroupRuleController.class);
    @Autowired
    private GroupRuleService    groupRuleService;
    @Autowired
    private GroupService        groupService;

    @RequestMapping("/findByGroupId")
    @ResponseBody
    public ResponsePage findByGroupId(@RequestParam("groupId") long groupId) {
        ResponsePage page = getResponsePage();
        List<GroupRuleBO> groupRuleBOs = null;
        try {
            groupRuleBOs = groupRuleService.findGroupRuleBOByGroupId(groupId);
            if (null == groupRuleBOs || groupRuleBOs.isEmpty()) {
                return page.emptyPage("未查询到结果");
            }
            return page.setJustList(groupRuleBOs, "查询成功");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }

    @RequestMapping("/switchBackUpDb")
    @ResponseBody
    public ResponsePage switchBackUpDb(@RequestParam("groupId") long groupId,
                                       @RequestParam("groupRuleId") long groupRuleId) {
        ResponsePage page = getResponsePage();
        List<GroupRuleBO> groupRuleBOs = null;
        try {
            GroupBO groupBO = groupService.findGroupBOById(groupId);
            if (null == groupBO) {
                return page.emptyPage("未查询到分组,请检查！");
            }
            groupRuleBOs = groupRuleService.findGroupRuleBOByGroupId(groupId);
            if (null == groupRuleBOs || groupRuleBOs.isEmpty()) {
                return page.emptyPage("未查询到分组规则,请检查！");
            }
            if (groupRuleBOs.size() > 2) {
                return page.emptyPage("查询到有多个备库请检查!");
            }
            boolean result = groupRuleService.switchBackUpDb(groupBO, groupRuleBOs);
            if (result) {
                return page.setSuccessMsg("切换成功！");
            } else {
                return page.setErrorMsg("切换失败！");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return page.setErrorMsg(e.getMessage());
        }
    }
}
